/**
* 登录页
*
**/
<template>
  <div class="login">
    <div class="switch-language">
      <el-dropdown size="large" :hide-timeout="50" placement="bottom-end" :hide-on-click="true">
        <el-icon color="#409EFC" size='25'>
          <Monitor />
        </el-icon>
        <template #dropdown>
          <el-dropdown-menu class="chang-lang">
            <el-dropdown-item v-for="item in configStore.lang.langArray" :key="item"
              @click="editDefaultLang(item.name)">
              {{ item.value }}
            </el-dropdown-item>
          </el-dropdown-menu>
        </template>
      </el-dropdown>
    </div>
    <div class='login-box'>
      <el-form @keyup.enter="submitForm(ruleFormRef)" ref="ruleFormRef" :model="form" status-icon :rules="rules"
        class="demo-ruleForm">
        <el-form-item prop="username">
          <el-input ref="usernameRef" v-model="form.username" autocomplete="off"
            :placeholder="$t('placeholder.username')">
            <template #prefix>
              <el-icon>
                <UserFilled />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input ref="passwordRef" type="password" v-model="form.password" :placeholder="$t('placeholder.password')">
            <template #prefix>
              <el-icon>
                <Unlock />
              </el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item prop="captcha">
          <el-row>
            <el-col :span="16">
              <el-input ref="captchaRef" v-model.number="form.captcha" autocomplete="off"
                :placeholder="$t('placeholder.captcha')">
                <template #prefix>
                  <el-icon>
                    <MoreFilled />
                  </el-icon>
                </template>
              </el-input>
            </el-col>
            <el-col :span="8">
              <img @click="onChangeCaptcha" class="captcha-img"
                :src="'https://demo.buildadmin.com/api/common/captcha?server=1' + '&id=' + state.captchaId" alt="" />
            </el-col>
          </el-row>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" :loading="form.loading" round @click="submitForm(ruleFormRef)">
            {{ $t('button.Sign in') }}
          </el-button>
        </el-form-item>
      </el-form>
    </div>
  </div>
</template>

<script setup lang="ts">
  import type { FormInstance } from 'element-plus';
  import { uuid } from "../utils/util";
  import { useUserInfo } from '../stores/userInfo'
  import { postlogin, login } from "../api/service";
  import router from "../router";
  import { useConfig } from "../stores/config";
  import { editDefaultLang } from '../lang'
  import { useI18n } from "vue-i18n";
  import { ElForm, ElInput, ElMessage } from "element-plus";


  const userInfo = useUserInfo()
  const configStore = useConfig()
  const { t } = useI18n()

  const ruleFormRef = ref < InstanceType < typeof ElForm >> ();
  const usernameRef = ref < InstanceType < typeof ElInput >> ();
  const passwordRef = ref < InstanceType < typeof ElInput >> ();
  const captchaRef = ref < InstanceType < typeof ElInput >> ();

  const state = reactive({
    captchaId: uuid(),
  })
  const focusInput = () => {
    if (form.username === '') {
      usernameRef.value!.focus()
    } else if (form.password === '') {
      passwordRef.value!.focus()
    } else if (form.captcha === '') {
      captchaRef.value!.focus()
    }
  }
  onMounted(() => {
    focusInput()
    onChangeCaptcha()
  })
  const onChangeCaptcha = () => {
    form.captcha = ''
    state.captchaId = uuid()
  }

  const validateUsername = (rule: any, value: any, callback: any) => {
    if (value === '') {
      callback(new Error(`${t('placeholder.username')}`))
    } else {
      callback()
    }
  }
  const validatePassword = (rule: any, value: any, callback: any) => {
    if (value === '') {
      callback(new Error(`${t('placeholder.password')}`))
    } else {
      callback()
    }
  }
  const validateCaptcha = (rule: any, value: any, callback: any) => {
    if (value === '') {
      callback(new Error(`${t('placeholder.captcha')}`))
    } else {
      callback()
    }
  }

  const form = reactive({
    username: '',
    password: '',
    captcha: '',
    captcha_id: '',
    loading: false
  })

  const rules = reactive({
    username: [{ validator: validateUsername, trigger: 'blur' }],
    password: [{ validator: validatePassword, trigger: 'blur' }],
    captcha: [{ validator: validateCaptcha, trigger: 'blur' }],
  })

  const submitForm = (formEl: FormInstance | undefined) => {
    if (!formEl) return
    formEl.validate((valid) => {
      if (valid) {
        form.loading = true
        form.captcha_id = state.captchaId
        router.push('/home')
        postlogin(form).then(res => {
          form.loading = false
          userInfo.dataFill(res.data.data.userinfo)
          ElMessage({
            message: res.data.msg,
            type: 'success',
          })
          router.push('/home')
        }).catch(error => {
          form.loading = false
          ElMessage.error(error)
        })
      } else {
        return false
      }
    })
  }
</script>

<style lang="less" scoped>
  .login {
    background: #294072;
    height: 100%;
    display: flex;
    align-items: center; // 垂直居中
    justify-content: center; // 水平居中

    .switch-language {
      position: absolute;
      top: 0.1rem;
      right: 0.5rem;
    }

    .login-box {
      background: #fff;
      width: 4rem;
      height: 4rem;
      display: flex;
      align-items: center; // 垂直居中
      justify-content: center; // 水平居中

      .el-form-item {
        margin: 0.2rem 0;

        button {
          width: 100%;
        }

        .captcha-img {
          margin-left: 0.05rem;
          width: 100%;
          height: 0.35rem;
        }
      }
    }
  }
</style>
